layui.use(['form','layer','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
		
	const tableVue=new Vue({
			el: '#userList',
			data:{
				  all_data:null,
				  tableIns:null
			},
			methods:{
				tablefill:function(){
					this.tableIns =table.render({
							cellMinWidth : 95,
							page : true,
							height : "full-125",
							elem: '#userList',
							id : "userListTable",
							cols: [[ //标题栏
								{type: "checkbox", fixed:"left", width:50},
								{field: 'userId', title: 'id', minWidth:100, align:"center"},
								{field: 'account', title: '用户名', minWidth:100, align:"center"},
								{field: 'type', title: '状态', align:'center',minWidth:50,templet:function(d){
										return d.type=='1'?'正常':'禁用'
								}},
								{field: 'email', title: '用户邮箱', minWidth:200, align:'center',templet:function(d){
												return '<a class="layui-blue" href="mailto:'+d.email+'">'+d.email+'</a>';
								}},
								{field: 'gender', title: '性别', minWidth:50, align:"center",templet:function(d){
										if(d.gender==null||d.gender=='')
											return '男'
										else
											return d.gender
											
								}},
								{field: 'autograph', title: '个性签名', minWidth:100, align:"center"},
								{field: 'createdTime', title: '注册时间', align:'center',minWidth:150,templet:function(d){
										var date = new Date(d.createdTime);
										Y = date.getFullYear() + '-';
										M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
										D = date.getDate() + ' ';
										h = date.getHours() + ':';
										m = date.getMinutes() + ':';
										s = date.getSeconds(); 
										return Y+M+D+h+m+s
								}},
								{field: 'lastPasswordResetDate', title: '最后修改密码', align:'center',minWidth:150,templet:function(d){
										var date = new Date(d.lastPasswordResetDate);
										Y = date.getFullYear() + '-';
										M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
										D = date.getDate() + ' ';
										h = date.getHours() + ':';
										m = date.getMinutes() + ':';
										s = date.getSeconds(); 
										return Y+M+D+h+m+s
								}},
							
								{title: '操作', minWidth:170, templet:'#userListBar',fixed:"right",align:"center"}
							]],data:this.all_data
							
					});
				},
				getUser:function(type){
					var url=global_url+'/admin/userAll'
					if(type!='1'&&type!=null){
						url+='/2'
					}else if(type=='1'){
						url+='/'+type
					}
					this.$http.post(url)
						.then(
						response=>{
							this.all_data=response.body.datas
							this.tablefill()
						},					
						response=>{
						})
				
				},
				
				deleteUser:function(data){
					this.$http.post(global_url+'/admin/banUser/'+data.userId)
						.then(
						response=>{
							layer.msg(response.body.datas)
							tableVue.getUser()
						},					
						response=>{
							layer.msg(response.body.status)
						})
				},
				search:function(username){
					this.$http.post(global_url+'/admin/user/'+username)
						.then(
						response=>{
							if(response.body.code=="-1"){
								layer.msg(response.body.datas)
								return
							}
							
							this.all_data=response.body.datas
							this.tablefill()
						},					
						response=>{
							layer.msg(response.body.status)
						})
				}
			}
		});
	tableVue.getUser()

  

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
			tableVue.search($(".searchVal").val())
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    //添加用户
    function addUser(edit){
			
			Vue.http.post(global_url+'/admin/rolePermissions/').then(
				response=>{
					var  permissions=response.body.datas;
					var index = layui.layer.open({
							title : "添加用户",
							type : 2,
							content : "userAdd.html",
							success : function(layero, index){
									var body = layui.layer.getChildFrame('body', index);
									if(edit){
											body.find(".userName").val(edit.account);  //登录名
											body.find(".userEmail").val(edit.email);  //邮箱
											body.find(".userSex input[value="+edit.gender+"]").prop("checked","checked");  //性别
											body.find(".userStatus").val(edit.type);    //用户状态
											body.find(".userDesc").text(edit.autograph);    //用户简介
											body.find(".userId").text(edit.userId)  //用户id
								
									}
									for(var i = 0 ; i< permissions.length;i++){
										body.find(".userGrade").append('<option value="'+permissions[i].name+'" >'+permissions[i].name+'</option>')
									}
									form.render();

									setTimeout(function(){
											layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
													tips: 3
											});
									},500)
							}
					})
					layui.layer.full(index);
					window.sessionStorage.setItem("index",index);
					//改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
					$(window).on("resize",function(){
							layui.layer.full(window.sessionStorage.getItem("index"));
					})
				},
				response=>{
					
				}
			)
        
    }
	
    $(".addNews_btn").click(function(){
        addUser();
    })

    //批量删除
//     $(".delAll_btn").click(function(){
//         var checkStatus = table.checkStatus('userListTable'),
//             data = checkStatus.data,
//             newsId = [];
//         if(data.length > 0) {
//             for (var i in data) {
//                 newsId.push(data[i].newsId);
//             }
//             layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
//                 // $.get("删除文章接口",{
//                 //     newsId : newsId  //将需要删除的newsId作为参数传入
//                 // },function(data){
//                 tableVue.tableIns.reload();
//                 layer.close(index);
//                 // })
//             })
//         }else{
//             layer.msg("请选择需要删除的用户");
//         }
    // })

	//查询所有正常用户
	$(".normal_btn").click(function(){
		tableVue.getUser("1")
	})
	
	//查询所有异常用户
	$(".extremely_btn").click(function(){
		tableVue.getUser("2")
	})
	
	
	
    //列表操作
    table.on('tool(userList)', function(obj){
        var layEvent = obj.event,
        data = obj.data;
        if(layEvent === 'edit'){ //编辑
            addUser(data);
        }else if(layEvent === 'usable'){ //启用禁用
            var _this = $(this),
                usableText = "是否确定禁用此用户？",
                btnText = "已禁用";
            if(_this.text()=="已禁用"){
                usableText = "是否确定启用此用户？",
                btnText = "已启用";
            }
            layer.confirm(usableText,{
                icon: 3,
                title:'系统提示',
                cancel : function(index){
                    layer.close(index);
                }
            },function(index){
                _this.text(btnText);
                layer.close(index);
            },function(index){
                layer.close(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定禁用此用户？',{icon:3, title:'提示信息'},function(index){
        					tableVue.deleteUser(data)
                  layer.close(index);
            });
        }
				
				
    });
	


})
